#!/bin/sh
### BEGIN INIT INFO
# Provides:          lkp-bootstrap
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: LKP bootstrap
# Description:       LKP bootstrap
### END INIT INFO

# Call this script at boot time.
# Keep it simple and stupid -- it will be installed in a number of rootfs.

# We can install lkp-bootstrap several places, so that at least one of them can
# take effect in a particular rootfs, and the follow up ones can check reboot
# the machine if the former one failed to do so.

mkdir -p /var/lock
[[ $(mkdir /var/lock/lkp-bootstrap.lock 2>&1) =~ 'File exists' ]] && sleep 333.3

if [ -s /lkp/run/lkp-bootstrap.pid ]; then
	pid=$(cat /lkp/run/lkp-bootstrap.pid)
	[ -d /proc/$pid ] && exit
	# the previous lkp-bootstrap init.d script failed to restart the machine
	echo "LKP bootstrap: first run may failed, retry rebooting"
	reboot
	exit
fi

read_kernel_cmdline_vars()
{
	[ -f /proc/cmdline ] || return 1

	for i in $(cat /proc/cmdline)
	do
		[ "${i#user=}" != "$i" ] && export $i
		[ "${i#job=}" != "$i" ] && export $i
		[ "${i#ip=}" != "$i" ] && export $i
		[ "${i#NO_NETWORK=}" != "$i" ] && export $i
		[ "${i#result_service}" != "$i" ] && export $i
	done
	return 0
}

read_kernel_cmdline_vars

# The job file is contained in the initrd -- no need to download it here.

# in case CONFIG_PROC_FS is not set, or job not passed via kernel cmdline
[ -n "$job" ] || export job=/lkp/scheduled/job.yaml
[ -e "$job" ] || export job=$(echo /lkp/scheduled/*.yaml)
[ -e "$job" ] || export job=$(echo /lkp/jobs/scheduled/*/*.yaml)

if [ ${job%.yaml} != $job ]; then
	export job_script=${job%.yaml}.sh
else
	export job_script=$job
fi

[ -e "$job_script" ] || {
	echo $job_script does not exist, quit from LKP
	exit 0 # to work with non-LKP boots
}


: "${user:=lkp}"
export LKP_USER=$user
export LKP_SRC=/lkp/$user/src

[ -n "$BASHPID" ] &&
export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

set +m

. $LKP_SRC/lib/env.sh
. $job_script
has_cmd export_top_env && export_top_env
has_cmd read_job_vars && read_job_vars

: "${DEBUG_LKP:=0}"
[ "$DEBUG_LKP" -ge 2 ] && set -x
[ "$DEBUG_LKP" -ge 1 ] && export DEBUG_LKP_PREFIX='bash -x'

if is_docker; then
	$DEBUG_LKP_PREFIX $LKP_SRC/bin/lkp-setup-rootfs && exit
fi

(
	$DEBUG_LKP_PREFIX $LKP_SRC/bin/lkp-setup-rootfs && exit

	# some reasonable debug time, if sleep is killed, it's likely
	# someone has login and want more time to look things around
	sleep 10m &&
	reboot
) &

mkdir -p /lkp/run
echo $! > /lkp/run/lkp-bootstrap.pid
